package internal

import (
	"doudizhu/msg"
	"fmt"
	"github.com/name5566/leaf/gate"
	"reflect"
	"strconv"
	"strings"
)

func init() {
	handler(&msg.User{}, handleuser)
	handler(&msg.JoinRoom{}, handleJoinroom)
	handler(&msg.PlayerReady{}, handlePlayerReady)
	handler(&msg.GameStart{}, handleGameStart)
	handler(&msg.ChuPai{}, handleChupai)
}

func handler(m, h interface{}) {
	skeleton.RegisterChanRPC(reflect.TypeOf(m), h)
}

func handleuser(args []interface{}) {
	m := args[0].(*msg.User)
	a := args[1].(gate.Agent)
	fmt.Println(m)
	m.Name = "after-" + m.Name
	a.WriteMsg(m)
}

func handleJoinroom(args []interface{}) {
	m := args[0].(*msg.JoinRoom)
	a := args[1].(gate.Agent)
	ars := msg.GetAllRooms()
	aps := msg.GetAllPlayers()
	p, err := aps.GetExistUser(m.Userid)
	if err != nil {
		a.WriteMsg(err.Error())
		return
	}
	if m.Roomid == "" {
		ars.NewRoom(p)
	} else {
		ars.JoinRoom(p, m.Roomid)
	}
	a.WriteMsg("success")
}

func handlePlayerReady(args []interface{}) {
	m := args[0].(*msg.PlayerReady)
	a := args[1].(gate.Agent)
	aps := msg.GetAllPlayers()
	p, err := aps.GetExistUser(m.Userid)
	if err != nil {
		a.WriteMsg(err.Error())
		return
	}
	p.Ready()
	a.WriteMsg("success")
}

func handleGameStart(args []interface{}) {
	m := args[0].(*msg.GameStart)
	a := args[1].(gate.Agent)
	ars := msg.GetAllRooms()
	room := ars.GetRoom(m.Roomid)
	err := room.StartGame()
	if err != nil {
		a.WriteMsg(err.Error())
		return
	}
	a.WriteMsg("success")
}

func handleChupai(args []interface{}) {
	m := args[0].(*msg.ChuPai)
	a := args[1].(gate.Agent)
	aps := msg.GetAllPlayers()
	p, err := aps.GetExistUser(m.Userid)
	if err != nil {
		a.WriteMsg(err.Error())
		return
	}
	cs := make([]msg.Card, 0, 0)
	for _, o := range m.Cards {
		ns := strings.Split(o, "-")
		num, _ := strconv.Atoi(ns[0])
		types, _ := strconv.Atoi(ns[1])
		cs = append(cs, msg.Card{num, types})
	}
	err = p.Chupai(cs)
	if err != nil {
		a.WriteMsg(err.Error())
		return
	}
	a.WriteMsg("success")
}
